package controllers

import (
	"log"

	"github.com/gin-gonic/gin"
	"github.com/globalsign/mgo/bson"
)

var CodeType struct {
	Once int64 // 兑换码只能领一次
	Many int64 // 兑换码能领多次
} = struct {
	Once int64
	Many int64
}{
	Once: 1,
	Many: 2,
}

type ExCode struct {
	Id    string `bson:"_id" json:"_id"`     // 兑换码
	APId  int64  `bson:"apId" json:"apId"`   // 活动礼包id
	CType int64  `bson:"cType" json:"cType"` // 类型
}

// 礼包查询条件
type ExCodeQuery struct {
	BaseRequest
	APId int64 `form:"apId"` // 活动礼包id
}

// 添加兑换码
func AddExCodes(ecLst []string, apId int64, cType int64) (err error) {
	for _, item := range ecLst {
		ec := &ExCode{
			Id:    item,
			APId:  apId,
			CType: cType,
		}
		err = GameDB.Insert("ExCode", ec)
		if err != nil {
			log.Println("添加兑换码失败", err)
		}
	}
	return
}

// 获取所有数据
func GetExCode(c *gin.Context) {
	var q ExCodeQuery
	if err := c.ShouldBindQuery(&q); err != nil {
		handleErr(c, 404, err.Error())
		return
	}
	mquery := make(map[string]interface{}, 0)
	mquery["apId"] = q.APId

	count, err := GameDB.Count("ExCode", mquery)
	if err != nil {
		log.Println("统计数据失败", err)
		handleErr(c, 404, err.Error())
		return
	}

	logList := make([]interface{}, 0)
	// err = GameDB.FindPageSort("ExCode", q.Page-1, q.PageNum, mquery, nil, nil, &logList)
	err = GameDB.FindAll("ExCode", mquery, nil, &logList)
	if err != nil {
		log.Println("查询数据失败", err)
		handleErr(c, 404, err.Error())
		return
	}
	handleOk(c, map[string]interface{}{"logList": logList, "count": count})
}

// 删除数据
func DelExCodes(apId int64) (err error) {
	err = GameDB.RemoveAll("ExCode", bson.M{"apId": apId})
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		log.Println("删除数据失败", err)
		return
	}
	return
}
